package server

import (
	"ctfo-platform-go/server/model"
	"database/sql"
	"errors"
	"net/http"

	"github.com/go-chi/render"
)

type ResponseData struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
	NoErrorRender
}

type NoErrorRender struct{}

// Render implements render.Renderer.
func (NoErrorRender) Render(w http.ResponseWriter, r *http.Request) error {
	return nil
}

func handle(w http.ResponseWriter, r *http.Request, data any, err error) {
	if err != nil {
		render.Render(w, r, errData(err))
		return
	}
	render.Render(w, r, successData(data))
}

func successData(data any) *ResponseData {
	return &ResponseData{
		Code:    200,
		Message: "请求成功",
		Data:    data,
	}

}

func errData(err error) *ResponseData {
	se, ok := err.(*model.CodeError)
	if ok {
		return &ResponseData{Code: se.Code, Message: se.Error()}
	}

	if errors.Is(err, sql.ErrNoRows) {
		return &ResponseData{Code: 400, Message: "记录不存在"}
	}

	return &ResponseData{Code: 500, Message: err.Error()}
}
